package top.mable.gateway.handler;



import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.LinkedHashMap;
import java.util.Map;
/**
 * @author taffywen
 * @date 2022/7/6 22:59
 */

@Order(-1)
@Configuration
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("[网关异常处理]请求路径:{}", exchange.getRequest().getPath(), ex);
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        errorAttributes.put("traceId", "");
        errorAttributes.put("code", determineHttpStatus(ex));
        errorAttributes.put("errMsg", determineMessage(ex));
        errorAttributes.put("data", null);
        return renderResult(exchange, errorAttributes);
    }

    private int determineHttpStatus(Throwable error) {
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getStatus().value();
        }
        ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(error.getClass(),
                ResponseStatus.class);
        if (responseStatus != null) {
            return responseStatus.code().value();
        }
        return org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR.value();
    }

    private String determineMessage(Throwable error) {
        if (error instanceof WebExchangeBindException) {
            return error.getMessage();
        }
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getReason();
        }
        ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(error.getClass(),
                ResponseStatus.class);
        if (responseStatus != null) {
            return responseStatus.reason();
        }
        return error.getMessage();
    }

    /**
     * 异步方式响应result
     *
     * @param exchange 渲染对象
     * @param result   待渲染的结果
     * @return null
     */
    public static Mono<Void> renderResult(ServerWebExchange exchange, Map result) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setRawStatusCode(HttpStatus.HTTP_OK);
        return response.writeWith(Mono.just(response.bufferFactory().wrap(JSONUtil.toJsonStr(result).getBytes())));
    }
}

